package cloudContact.DAO;

import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.DuplicateKeyException;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

import cloudContact.MyDAOException;

public class AddressDAO {
	private BeanFactory<Address> factory;
	
	private static AddressDAO addressDAO;
	
	public static AddressDAO getInstance() throws RollbackException
	{
		if (addressDAO == null)
		{
			addressDAO = new AddressDAO();
		}
		return addressDAO;
	}

	private AddressDAO() {
       
        	String jdbcDriver = "com.mysql.jdbc.Driver";
            String jdbcURL    = "jdbc:mysql:///finalproject";
            String userName   = "anonymous";
            String password   = "";
            String tableName = "addresses";
            BeanTable.useJDBC(jdbcDriver,jdbcURL,userName,password);
        	BeanTable<Address> table = BeanTable.getSQLInstance(Address.class,tableName,jdbcDriver,jdbcURL);
            if (!table.exists()) {
                table.create("AddressId");   // provide the primary key property(s)
            }
            factory = table.getFactory();
	}

	public void create(Address newAddress) throws MyDAOException {
        try {
        	Transaction.begin();
        	Address dbAddress = factory.create();
        	factory.copyInto(newAddress, dbAddress);
            Transaction.commit();
            newAddress.setAddressId(dbAddress.getAddressId());
        } catch (DuplicateKeyException e) {
            throw new MyDAOException("Address already exists: "+ newAddress.getAddressId());
        } catch (RollbackException e) {
            throw new MyDAOException(e);
        }
    }

    public Address lookup(int id) throws MyDAOException {
        try {
            return factory.lookup(id);
        } catch (RollbackException e) {
            throw new MyDAOException(e);
        }
    }
    
    public void delete(int id) throws MyDAOException{
    	try {
			factory.delete(id);
		} catch (RollbackException e) {
			throw new MyDAOException(e);
		}
    }
}
